import axios from "axios";
import { Toast } from "vant";
import store from "../store/index";
import qs from "qs";
const instance = axios.create({
  withCredentials: false,
  timeout: 200000,
});
const handleResponse = function (res) {
  store.commit("setLoading", false);
  const {
    data: { code, data, msg },
  } = res;
  let rt = {};
  switch (code) {
    case 200:
      rt = data;
      break;
    case 403:
    case 401:
      rt = new Error(msg);
      Promise.resolve().then(() => {
        Toast({
          type: "fail",
          message: msg,
        });
      });
      break;
    default:
      rt = new Error(msg);
      Toast({
        type: "fail",
        message: msg,
      });
  }
  if (rt instanceof Error) {
    throw rt;
  } else {
    return rt;
  }
};
// switch(process.env.NODE_ENV){
// 	case 'production':
// 		axios.defaults.baseURL='https://221.7.196.174:28699';
// 		break;
// 	case 'test':
// 		axios.defaults.baseURL="https://221.7.196.174:28699";
// 		break;
// 	default:
// 		axios.defaults.baseURL='https://221.7.196.174:28699'
// }
instance.defaults.baseURL = "https://221.7.196.174:28699";
//instance.defaults.baseURL = "http://ty.dev.tmusoft.com:22216";
// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    if (config.requestBase == "gettoken") {
      config.baseURL = "https://221.7.196.174:28682"; // 取到环境变量：baseURL
      //config.baseURL = " http://ty.dev.tmusoft.com:22211";
    }
    store.commit("setLoading", true);
    config.headers = {
      ...config.headers,
      USER_TOKEN: store.state.token,
    };
    config.params = {
      ...config.params,
      _t: Date.now(),
    };
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    return handleResponse(response);
  },
  function (error) {
    handleResponse(error.response);
    return Promise.reject(error);
  }
);

export default instance;
